package com.sdx.console.customer.service;

import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.BaseService;
import com.ibeetl.admin.core.util.PlatformException;
import com.sdx.common.utils.MD5;
import com.sdx.common.utils.Utils;
import com.sdx.console.customer.dao.CustomerInfoDao;
import com.sdx.console.customer.entity.ChoiceScore;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.entity.CustomerUserMap;
import com.sdx.console.entity.CustomerAccount;
import com.sdx.console.person.dao.CustomerExtInfoDao;
import com.sdx.console.person.entity.CustomerExtInfo;
import com.sdx.console.transaction.entity.FinTransaction;
import com.sdx.console.utils.CodeUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 会员管理 Service
 */

@Service
@Transactional
public class CustomerInfoService extends BaseService<CustomerInfo>{

	private static final String PASSWD_SALT = "owrhgow38";
	private static final String CHANNEL = "sysimp";

    @Resource
	private CustomerInfoDao customerInfoDao;

    @Resource
    private CustomerExtInfoDao customerExtInfoDao;

	public void revokeRole(String customerId,String remark) {
		customerInfoDao.revokeRole(customerId,remark);
	}
	public String customersRole(List<String> ids) {
		return customerInfoDao.customersRole(ids);
	}
    public PageQuery<CustomerInfo>queryByCondition(PageQuery query){
        PageQuery ret =  customerInfoDao.queryByCondition(query);
        queryListAfter(ret.getList());
        return ret;
    }

	public PageQuery<CustomerInfo>queryByConditionCustomer(PageQuery query){
		PageQuery ret =  customerInfoDao.queryByConditionCustomer(query);
		queryListAfter(ret.getList());
		return ret;
	}

    public void batchDelCustomerInfo(List<String> ids){
        try {
            customerInfoDao.batchDelCustomerInfoByIds(ids);
        } catch (Exception e) {
            throw new PlatformException("批量删除会员管理失败", e);
        }
    }

	/**
	 * 转成老师
	 * @param customerId
	 * @param updatedBy
	 * @param updatedName
	 */
	public void setTearch(String customerId,Integer updatedBy,String updatedName) {
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setCustomerId(customerId);
		customerInfo.setUpdatedBy(updatedBy);
		customerInfo.setUpdatedName(updatedName);
		customerInfo.setUpdatedTime(new Date());
		customerInfo.setIsTeacher(1);
		customerInfoDao.updateTemplateById(customerInfo);
		customerInfo = customerInfoDao.single(customerId);
		CustomerExtInfo customerExtInfo = customerExtInfoDao.single(customerId);
		if (customerExtInfo==null) {
			customerExtInfo = new CustomerExtInfo();
			customerExtInfo.setCustomerId(customerId);
			customerExtInfo.setCustomerName(customerInfo.getWxUname());
			customerExtInfo.setCustStatus(1);
			customerExtInfo.setZhiboPower(0);
			customerExtInfo.setUpdatedBy(updatedBy);
			customerExtInfo.setUpdatedName(updatedName);
			customerExtInfo.setUpdatedTime(new Date());
			customerExtInfoDao.insertTemplate(customerExtInfo);
		}

    }

	/**
	 * 转成员工
	 * @param customerId
	 * @param userId
	 */
	public void saveEmp(CoreUser coreUser,String customerId, Integer userId) {
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setCustomerId(customerId);
		customerInfo.setCustomerType("0");
		customerInfo.setUpdatedBy(coreUser.getId().intValue());
		customerInfo.setUpdatedName(coreUser.getName());
		customerInfo.setUpdatedTime(new Date());
		customerInfoDao.updateTemplateById(customerInfo);

		CustomerUserMap map = customerInfoDao.getSQLManager().single(CustomerUserMap.class,customerId);
		if (map==null) {
			map = new CustomerUserMap();
			map.setCustomerId(customerId);
			map.setUserId(userId);
			map.setCreatedBy(coreUser.getId().intValue());
			map.setCreatedName(coreUser.getName());
			map.setCreatedTime(new Date());
			customerInfoDao.getSQLManager().insert(map);
		}
    }
	public List<CustomerUserMap> selectUserMap(String customerId,Integer userId) {
		return customerInfoDao.selectUserMap(customerId, userId);
	}

	public Integer getUserId(String customerId) {
		List<CustomerUserMap> list = selectUserMap(customerId,null);
		if (list.size()>0) {
			return list.get(0).getUserId();
		} else {
			return null;
		}
	}

	public String getCustomerId(Integer userId) {
		List<CustomerUserMap> list = selectUserMap(null,userId);
		if (list.size()>0) {
			return list.get(0).getCustomerId();
		} else {
			return null;
		}
	}

	public CustomerAccount inserCust(String phone,Integer tenantId){
		CustomerAccount account = new CustomerAccount();
		account.setRegType("c");
		account.setRegAccount(phone);
		CustomerAccount customerAccount = sqlManager.templateOne(account);
		if(customerAccount!=null){
			return customerAccount;
		}
		//注册会员
		String customerId = Utils.uuid();
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setCustomerId(customerId);
		customerInfo.setRegType("c");
		customerInfo.setIsTeacher(0);
		customerInfo.setPhone(phone);
		customerInfo.setSourceId(phone);
		customerInfo.setChannel(CHANNEL);
		customerInfo.setCustStatus(1);
		customerInfo.setTenantId(tenantId);
		customerInfo.setRegisterTime(new Date());
		save(customerInfo);
		//插入
		return insertAccount(customerId, phone);
	}

	/**
	 *  查询 CustomerAccount
	 * @param customerId
	 * @param phone
	 * @return
	 */
	public CustomerAccount insertAccount(String customerId,String phone){
		String passwd = CodeUtils.getCode(6);
		CustomerAccount account = new CustomerAccount();
		account.setCustomerId(customerId);
		account.setRegType("c");
		account.setRegAccount(phone);
		account.setPasswd(MD5.MD5Encode(PASSWD_SALT + MD5.MD5Encode(passwd)));
		account.setAccountStatus(1);
		account.setRegTime(new Date());
		sqlManager.insertTemplate(account);
		account.setPasswd(passwd);
		return account;
	}

	public String inserFinTrans(String customerId,Integer tenantId,String orderId){
		FinTransaction finTransaction = new FinTransaction();
		String transactionId =  Utils.uuid();
		finTransaction.setTransactionId(transactionId);
		finTransaction.setUserId(customerId);
		finTransaction.setTenantId(tenantId);
		finTransaction.setOrderId(orderId);
		finTransaction.setOrderType(301);
		finTransaction.setPayMethod(100);
		finTransaction.setTotalMoney(0L);
		finTransaction.setPayFlag(2);
		finTransaction.setCreateTime(new Date());
		finTransaction.setPayTime(new Date());
		finTransaction.setTradeMemo("热点精读后台开通");
		finTransaction.setChannel(CHANNEL);
		sqlManager.insertTemplate(finTransaction);
		return transactionId;
	}

	public void revokeRead(List<String> ids,String remark) {
		customerInfoDao.revokeRead(ids,remark);
	}

    public ChoiceScore queryChoiceScore(String customerId, Integer choiceYear, Integer majorType, String provinceId) {
		return customerInfoDao.queryChoiceScore(customerId,choiceYear,majorType,provinceId);
    }

	public PageQuery<CustomerInfo> queryEolByCondition(PageQuery query){
		PageQuery ret =  customerInfoDao.queryEolByCondition(query);
		queryListAfter(ret.getList());
		return ret;
	}
}
